package com.dreamsky.life.controller;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import com.dreamsky.life.interceptor.LifeInterceptorStack;
import com.dreamsky.life.model.ElectricControl;
import com.dreamsky.life.util.Const;
import com.dreamsky.life.util.StringUtils;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.core.Controller;

/**
 * Electric Controller
 * 
 * @author ssh
 * 
 */
@Before(LifeInterceptorStack.class)
public class ElectricController extends Controller {

	/**
	 * 用户发出电器控制状态
	 */
	public void controlState() {
		
		// 通过提交的电器ID和控制动作生成一条电器控制记录
		ElectricControl ec = getModel(ElectricControl.class);
		ec.set("user_id", getSessionAttr(Const.USER_ID_KEY));
		ec.set("id", StringUtils.randomId());
		ec.set("cl_time", new Date());

		boolean isSuccess = ec.save();

		setAttr("success", isSuccess);
		setAttr("msg", isSuccess ? "" : "请再试一次");

		renderJson(new String[] { "success", "msg" });
	}

	/**
	 * pi得到用户电器的动作
	 */
	@ClearInterceptor
	public void electric() {
		String userId = getPara("userId");

		List<ElectricControl> list = ElectricControl.dao
				.getUserElectricControll(userId);

		if (list == null) {
			setAttr("success", false);
		} else {
			setAttr("success", true);
			setAttr("eleControl", list);
		}

		renderJson(new String[] { "success", "eleControl" });

	}

	/**
	 * pi回传电器完成动作
	 */
	public void sendState() {
		ElectricControl ec = getModel(ElectricControl.class);
		boolean isSuccess = ec.update();

		renderJson("success", isSuccess);
	}
}
